package com.slkj.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.slkj.dto.Result;
import com.slkj.dto.StatusCode;
import com.slkj.entity.PageResult;
import com.slkj.pojo.*;
import com.slkj.service.*;
import com.slkj.util.IdWorker;
import com.slkj.vo.DocumentVO;
import lombok.extern.slf4j.Slf4j;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.*;

@Slf4j
@RestController
@RequestMapping("/${address.prefix}/doc")
public class DocumentAllController {

    @Autowired
    private DocumentAllService documentAllService;
    @Autowired
    private DocInspectTypeService docInspectTypeService;
    @Autowired
    private DocSpeedLevelService speedLevelService;
    @Autowired
    private DocUserInfoService userInfoService;
    @Autowired
    private IdWorker idWorker;
    @Autowired
    private DocsReplyLogService replyLogService;


    /**
     * 显示除了1开头领导其他单位的信息
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/userInfo/{page}/{pageSize}")
    public  List<String>  findAllUserInfo(@PathVariable Integer page, @PathVariable Integer pageSize){
        System.out.println("显示除了1开头领导其他单位的信息----");
        List<DocUserInfo> allUserInfo = userInfoService.findUserNOLeader(page,pageSize);
        List<String> names=new ArrayList<>();
        for (DocUserInfo docUserInfo : allUserInfo) {
            names.add(docUserInfo.getName());
        }
        return names;
    }
    /**
     * 督查四种格式格式
     * @return
     */
    @GetMapping("/inspectType")
    public List<String> findAllDocInspectType(){
        System.out.println("显示所有督查格式----");
        List<DocInspectType> allDocInspect = docInspectTypeService.findAllDocInspect();
        List<String> inspectTypes=new ArrayList<>();
        for (DocInspectType docInspectType : allDocInspect) {
            inspectTypes.add( docInspectType.getInspectType()) ;
        }
        return inspectTypes;
    }
    /**
     * 发文速度缓急
     * @return
     */
    @GetMapping("/speed")
    public List<String> findAllSpeedLevel(){
        System.out.println("显示所有缓急速度----");
        List<DocSpeedLevel> allSpeedLevels = speedLevelService.findAllSpeedLevel();
        List<String> speedLevels=new ArrayList<>();
        for (DocSpeedLevel docSpeedLevel : allSpeedLevels) {
            speedLevels.add(docSpeedLevel.getSpeedLevel());
        }
        return speedLevels;
    }

    /**
     * 多条件搜索
     * @param data
     * @param page
     * @param pageSize
     * @return
     */
    @PostMapping("/search/{page}/{pageSize}")
    public Result findDocList(@RequestBody String data, @PathVariable Integer page, @PathVariable Integer pageSize){
        Map map = JSONObject.parseObject(data, Map.class);
        System.out.println(map);
        Page<DocumentAll> listDocument = documentAllService.findListDocument(map, page, pageSize);
        List<DocumentVO> list=new ArrayList<>();
        for (DocumentAll documentAll : listDocument) {
            DocumentVO documentVO = new DocumentVO();
            BeanUtils.copyProperties(documentAll,documentVO);
            list.add(documentVO);
        }
        PageResult pageResult = new PageResult(listDocument.getTotal(), list);
        return new Result(true, StatusCode.OK,"多条件搜索成功",pageResult);
    }

    /**
     * 发文..
     * @param data
     * @return
     */
    @PostMapping("/dispatch")
    public Result add(@RequestBody String data){
        log.info("发送公文，并保存公文" + data);
        DocumentAll documentAll = JSON.parseObject(data, DocumentAll.class);
        //String sendPeople = documentAll.getSendPeople();//测试用"sendPeople":"姜昊",
        DocUserInfo userinfo = (DocUserInfo)SecurityUtils.getSubject().getSession().getAttribute("userinfo");
        String name = userinfo.getName();

        documentAll.setSendPeople(name);
        //生成UUID
        String uuid=String.valueOf(idWorker.nextId());
        documentAll.setDocUuid(uuid);
        documentAll.setAddTime(LocalDateTime.now());
        documentAll.setDocStatus("已发送");
        //1新建一条公文
        documentAllService.addDocument(documentAll);
        System.out.println("documentAll新建一条公文>>>" + documentAll);
        System.out.println("------------------新建公文写入数据库完成---------------------");
        Integer i=1;

        //2.1创建Log日志.生成第一条.。。发文人
        DocsReplyLog docsReplyLogSendPeople = new DocsReplyLog();
        docsReplyLogSendPeople.setDocUuid(uuid);
        docsReplyLogSendPeople.setReplyNum(i ++);
        //报送材料的人，是自己
        docsReplyLogSendPeople.setReceivePeople(name);
        docsReplyLogSendPeople.setReceivePeopleStatus("生成正文");
        docsReplyLogSendPeople.setReplyTime(LocalDateTime.now());
       replyLogService.addDocsReplyLog(docsReplyLogSendPeople);
        System.out.println("Log日志.生成第一条.发文人>>>" + docsReplyLogSendPeople);
        System.out.println("------------------Log日志第一条.发文人完成---------------------");

        //2.2创建Log日志.生成第2..条.。。抄送人
        String copyPeople = documentAll.getCopyPeople();
        if(!StringUtils.isEmpty(copyPeople)){
            String[] split = copyPeople.split(",");
            for (String splName: split) {
                DocsReplyLog logCopyPeople = new DocsReplyLog();
                logCopyPeople.setDocUuid(uuid);
                logCopyPeople.setReceivePeople(splName);
                logCopyPeople.setReceivePeopleStatus("未读");
                logCopyPeople.setReplyNum(i ++);
                 replyLogService.addDocsReplyLog(logCopyPeople);
                System.out.println("------------------Log日志第2次.抄送人---------------------");
                System.out.println("Log日志.生成第2条.抄送人>>>" + logCopyPeople);
            }
        }
        //2.3创建Log日志.所有收件人
        String receivePeoples = documentAll.getReceivePeoples();
        if(!StringUtils.isEmpty(receivePeoples)){
            String[] split = receivePeoples.split(",");
            for (String receivePeople : split) {
                DocsReplyLog logRceivePeople = new DocsReplyLog();
                logRceivePeople.setDocUuid(uuid);
                System.out.println("接收人信息receivePeople>>>" + receivePeople);
                logRceivePeople.setReceivePeople(receivePeople);
                logRceivePeople.setReceivePeopleStatus("未读");
                logRceivePeople.setReplyNum(i ++);
                  replyLogService.addDocsReplyLog(logRceivePeople);
                System.out.println("------------------Log日志第3次.接收人---------------------");
                System.out.println("Log日志第3次.接收人>>>" + logRceivePeople);
            }
        }
        return new Result(true, StatusCode.OK,"添加公文成功",uuid);
    }

    /**
     * 显示公文详细内容。。如果人名编号不为1 ，则更改LOG的阅读receivePeopleStatus状态。"已读"。
     * @param data
     * @return
     */
    @PostMapping("/content")
    public Result document(@RequestBody String data){
        JSONObject jsonObject = JSONObject.parseObject(data);
        String docUuid = jsonObject.getString("docUuid");
        DocUserInfo userinfo = (DocUserInfo)SecurityUtils.getSubject().getSession().getAttribute("userinfo");
        String name = userinfo.getName();
        DocumentAll docByUUid = documentAllService.findByUUid(docUuid);
        String sendPeople = docByUUid.getSendPeople();
        //如果发件人。。和登录这个人名字不一致..，则更改LOG的阅读receivePeopleStatus状态。"已读"。
        if(!sendPeople.equals(name)){
            replyLogService.readByUUIDAndName(docUuid,name);
        }
        return new Result(true, StatusCode.OK,"显示公文",docByUUid);
    }



    /**
     * 显示自己发文
     * @return
     */
    @GetMapping("/sendSelf/{page}/{pageSize}")
    private Result findSend(@PathVariable Integer page, @PathVariable Integer pageSize){
        DocUserInfo userinfo =(DocUserInfo) SecurityUtils.getSubject().getSession().getAttribute("userinfo");
        String name = userinfo.getName();
        Map<String,String> map=new HashMap<>();
        map.put("sendPeople",name);
        Page<DocumentAll> listDocument = documentAllService.findListDocument(map, page, pageSize);
        List<DocumentVO> list=new ArrayList<>();
        for (DocumentAll documentAll : listDocument) {
            DocumentVO documentVO = new DocumentVO();
            BeanUtils.copyProperties(documentAll,documentVO);
            list.add(documentVO);
        }
        PageResult pageResult = new PageResult(listDocument.getTotal(), list);
        return new Result(true, StatusCode.OK,"自己发文成功",pageResult);
    }

    /**显示本人收文  测试用   @PostMapping   @RequestBody String data,
     * @return
     */
    @GetMapping("/receive")
    public Result receivePeople(){
       /* JSONObject jsonObject = JSONObject.parseObject(data);
        String name = jsonObject.getString("name");*/
          DocUserInfo userinfo =(DocUserInfo) SecurityUtils.getSubject().getSession().getAttribute("userinfo");
         String name = userinfo.getName();
        //在发文日志中。。显示
        Set<String> uuidByName = replyLogService.findUuidByName(name);
        //如果收件人名字。和。。
        System.out.println("list>>" + uuidByName);
        //如果无数据返回
        if (uuidByName.size()<0){
           return new Result(true,StatusCode.OK,"没有收到文件"); }
        //有数据放到VO
        List<DocumentVO>  voList=new ArrayList<>();
        for (String uuid : uuidByName) {
            DocumentAll documentAll = documentAllService.findByUUid(uuid);
            DocumentVO documentVO = new DocumentVO();
            BeanUtils.copyProperties(documentAll,documentVO);
            System.out.println(   "documentVO>>" +documentVO);
            voList.add(documentVO);
        }
        PageResult pageResult = new PageResult((long)voList.size(),voList);
        return new Result(true,StatusCode.OK,"显示自身收文",pageResult);

    }

    /**
     * 显示自己的所有的收藏文件
     * @return
     */
    @GetMapping("/showCollect")
    public Result showCollect(){
        //显示1本身的。2收藏的。
        log.info("显示自己收藏公文");
        DocUserInfo userinfo =(DocUserInfo) SecurityUtils.getSubject().getSession().getAttribute("userinfo");
        String name = userinfo.getName();
        log.info("name>>" + name);
        //通过名字。或者账号。和查
        List<String> uuidByCollectAndName = replyLogService.findUUIDByCollectAndName(name);
        if (uuidByCollectAndName.size()<=0){
            return null;
        }
        List<DocumentVO> documentVOList=new ArrayList<>();
        for (String uuid : uuidByCollectAndName) {
            DocumentAll document = documentAllService.findByUUid(uuid);
            DocumentVO documentVO = new DocumentVO();
            BeanUtils.copyProperties(document,documentVO);
            documentVOList.add(documentVO);
        }
        // Page<DocumentAll> byCollectAndName = documentAllService.findByCollectAndName(name, page, pageSize);
        PageResult pageResult = new PageResult((long) documentVOList.size(), documentVOList);
        return new Result(true, StatusCode.OK,"自己发文成功",pageResult);
    }





}
